#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import json
import time
from flask import Response, request
from aes_utils import aes_decrypt
from database.flask_log import FlaskLog
from tool import Log_Parser

log = Log_Parser()
flaskLog = None


#---------------------------------#
#******#      Message      #******#
#---------------------------------#
def MessageOK():
    '''返回正常信息'''
    return {"code": 200, "message": "ok", "data": dict()}


def MessageERROR(message):
    '''返回错误信息'''
    return {"code": -1, "message": message, "data": dict()}


#---------------------------------#
#******#   ResponseData    #******#
#---------------------------------#
def ResponseDataForJson(data):
    '''返回Json格式数据'''
    return Response(json.dumps(data), mimetype='application/json')


#---------------------------------#
#******#   before_request    #******#
#---------------------------------#
def before_user(request):
    ret_dat = {}
    ret_dat["msg"] = 'success'
    ret_dat["code"] = 0
    # print("-----------------common-before_request--------------")
    # print(request.headers)
    
    # try:
    #     global flaskLog
    #     if not flaskLog:
    #         flaskLog = FlaskLog()
    #     flaskLog.insertRequestLog(request)
    # except Exception as err:
    #     print("[FlaskLog] Failed __CreateTable: {}".format(str(err)))
    
        # print(err)
    #  压测时使用  start
    # url = request.path
    # import threading
    # print("url {} thread {} ".format(url,threading.current_thread().name))
    # if not url == "/check_update":
    #     time.sleep(1000*10000)
    #  压测时使用  end
    try:
        # print("-----before_user 2-------")
        url = request.path  # 当前请求的URL
        # print(url)
        # return None
        # passUrl = ["/login", "/account_create","account_list"]
        # if url in passUrl:
        #     return None
        #     pass
       
        # time_now = int(time.time())  # time.time()类型 float 当前时间
       
        # print(time_now)
        # time_local = time.localtime(time_now)
        # dt = time.strftime("%Y-%m-%d %H:%M:%S",time_local)
        # print(dt)

        aotbot_sign = request.headers.get("Aotbot-Sign")
        # print(aotbot_sign)
        if not aotbot_sign:
            aotbot_sign = request.headers.get("aotbot-sign")

        if not aotbot_sign:
            ret_dat = {}
            ret_dat["msg"] = 'Please log in'
            ret_dat["code"] = 203
            return ret_dat

        timestamp = int(eval(aes_decrypt(aotbot_sign)))

        # print("before_user timestamp： {} ".format(timestamp))
        if  not timestamp:  # 当前时间-time大于20s直接返回错误
            # print(time_now - timestamp)
            ret_dat = {}
            ret_dat["msg"] = '解密失败'
            ret_dat["data"] = timestamp
            ret_dat["code"] = 408
            return ret_dat

        # diff=time_now - timestamp
        # print("before_user timestamp： {}  diff:{}".format(timestamp, diff))
        # if  diff> 30:  # 当前时间-time大于20s直接返回错误
        #     # print(time_now - timestamp)
        #     ret_dat = {}
        #     ret_dat["msg"] = 'Request Time-out'
        #     ret_dat["data"] = time_now
        #     ret_dat["code"] = 408
        #     return ret_dat

        # time_local = time.localtime(timestamp)
        # dt = time.strftime("%Y-%m-%d %H:%M:%S",time_local)
        # print(dt)

    except Exception as error:
        print(error)
        ret_dat["code"] = 400
        ret_dat["msg"] = str(error)

        err_msg = "[before_user]Failed to set robot parameters: {}".format(
            error)
        log.LogError("common", err_msg)
        return ret_dat


def guess_mimetype(absolute_file_path):
    _types_map_default = {
        '.js': 'application/javascript',
        '.mjs': 'application/javascript',
        '.json': 'application/json',
        '.webmanifest': 'application/manifest+json',
        '.doc': 'application/msword',
        '.dot': 'application/msword',
        '.wiz': 'application/msword',
        '.bin': 'application/octet-stream',
        '.a': 'application/octet-stream',
        '.dll': 'application/octet-stream',
        '.exe': 'application/octet-stream',
        '.o': 'application/octet-stream',
        '.obj': 'application/octet-stream',
        '.so': 'application/octet-stream',
        '.oda': 'application/oda',
        '.pdf': 'application/pdf',
        '.p7c': 'application/pkcs7-mime',
        '.ps': 'application/postscript',
        '.ai': 'application/postscript',
        '.eps': 'application/postscript',
        '.m3u': 'application/vnd.apple.mpegurl',
        '.m3u8': 'application/vnd.apple.mpegurl',
        '.xls': 'application/vnd.ms-excel',
        '.xlb': 'application/vnd.ms-excel',
        '.ppt': 'application/vnd.ms-powerpoint',
        '.pot': 'application/vnd.ms-powerpoint',
        '.ppa': 'application/vnd.ms-powerpoint',
        '.pps': 'application/vnd.ms-powerpoint',
        '.pwz': 'application/vnd.ms-powerpoint',
        '.wasm': 'application/wasm',
        '.bcpio': 'application/x-bcpio',
        '.cpio': 'application/x-cpio',
        '.csh': 'application/x-csh',
        '.dvi': 'application/x-dvi',
        '.gtar': 'application/x-gtar',
        '.hdf': 'application/x-hdf',
        '.latex': 'application/x-latex',
        '.mif': 'application/x-mif',
        '.cdf': 'application/x-netcdf',
        '.nc': 'application/x-netcdf',
        '.p12': 'application/x-pkcs12',
        '.pfx': 'application/x-pkcs12',
        '.ram': 'application/x-pn-realaudio',
        '.pyc': 'application/x-python-code',
        '.pyo': 'application/x-python-code',
        '.sh': 'application/x-sh',
        '.shar': 'application/x-shar',
        '.swf': 'application/x-shockwave-flash',
        '.sv4cpio': 'application/x-sv4cpio',
        '.sv4crc': 'application/x-sv4crc',
        '.tar': 'application/x-tar',
        '.tcl': 'application/x-tcl',
        '.tex': 'application/x-tex',
        '.texi': 'application/x-texinfo',
        '.texinfo': 'application/x-texinfo',
        '.roff': 'application/x-troff',
        '.t': 'application/x-troff',
        '.tr': 'application/x-troff',
        '.man': 'application/x-troff-man',
        '.me': 'application/x-troff-me',
        '.ms': 'application/x-troff-ms',
        '.ustar': 'application/x-ustar',
        '.src': 'application/x-wais-source',
        '.xsl': 'application/xml',
        '.rdf': 'application/xml',
        '.wsdl': 'application/xml',
        '.xpdl': 'application/xml',
        '.zip': 'application/zip',
        '.au': 'audio/basic',
        '.snd': 'audio/basic',
        '.mp3': 'audio/mpeg',
        '.mp2': 'audio/mpeg',
        '.aif': 'audio/x-aiff',
        '.aifc': 'audio/x-aiff',
        '.aiff': 'audio/x-aiff',
        '.ra': 'audio/x-pn-realaudio',
        '.wav': 'audio/x-wav',
        '.bmp': 'image/bmp',
        '.gif': 'image/gif',
        '.ief': 'image/ief',
        '.jpg': 'image/jpeg',
        '.jpe': 'image/jpeg',
        '.jpeg': 'image/jpeg',
        '.png': 'image/png',
        '.svg': 'image/svg+xml',
        '.tiff': 'image/tiff',
        '.tif': 'image/tiff',
        '.ico': 'image/vnd.microsoft.icon',
        '.ras': 'image/x-cmu-raster',
        '.bmp': 'image/x-ms-bmp',
        '.pnm': 'image/x-portable-anymap',
        '.pbm': 'image/x-portable-bitmap',
        '.pgm': 'image/x-portable-graymap',
        '.ppm': 'image/x-portable-pixmap',
        '.rgb': 'image/x-rgb',
        '.xbm': 'image/x-xbitmap',
        '.xpm': 'image/x-xpixmap',
        '.xwd': 'image/x-xwindowdump',
        '.eml': 'message/rfc822',
        '.mht': 'message/rfc822',
        '.mhtml': 'message/rfc822',
        '.nws': 'message/rfc822',
        '.css': 'text/css',
        '.csv': 'text/csv',
        '.html': 'text/html',
        '.htm': 'text/html',
        '.txt': 'text/plain',
        '.bat': 'text/plain',
        '.c': 'text/plain',
        '.h': 'text/plain',
        '.ksh': 'text/plain',
        '.pl': 'text/plain',
        '.rtx': 'text/richtext',
        '.tsv': 'text/tab-separated-values',
        '.py': 'text/x-python',
        '.etx': 'text/x-setext',
        '.sgm': 'text/x-sgml',
        '.sgml': 'text/x-sgml',
        '.vcf': 'text/x-vcard',
        '.xml': 'text/xml',
        '.mp4': 'video/mp4',
        '.mpeg': 'video/mpeg',
        '.m1v': 'video/mpeg',
        '.mpa': 'video/mpeg',
        '.mpe': 'video/mpeg',
        '.mpg': 'video/mpeg',
        '.mov': 'video/quicktime',
        '.qt': 'video/quicktime',
        '.webm': 'video/webm',
        '.avi': 'video/x-msvideo',
        '.movie': 'video/x-sgi-movie',
    }
    for item in _types_map_default.keys():
        if absolute_file_path.endswith(item):
            return _types_map_default[item]
    return None


def getRequestInfo(request):
    return "method: {}, url: {}, remote_addr: {}, Platform: {}, User: {}".format(
            request.method, request.url, request.remote_addr
            , request.headers.get("Aoting-Plaform") if "Aoting-Plaform" in request.headers else ""
            , request.headers.get("Aoting-User") if "Aoting-User" in request.headers else ""
        )

# PAD
# ('before', <Request 'http://192.168.9.200:5000/check_update' [GET]>)
# ('data', '')
# ('headers', EnvironHeaders([('Aotbot-Sign', u'hpT/NqKlvjRIeLEq+lqTIg=='), ('User-Agent', u'Mozilla/5.0 (Linux; U; Android 5.1; zh-cn; K17 Build/LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Mobile Safari/537.36'), ('Connection', u'close,close'), ('Host', u'192.168.9.200:5000'), ('Aoting-Plaform', u'PAD'), ('Aoting-User', u'-'), ('Accept-Language', u'zh-CN,zh;q=0.8'), ('Accept-Encoding', u'identity')]))
# ('json', None)

# Apifox
# ('before', <Request 'http://192.168.9.200:5000/utils_ctrl_default_list' [POST]>)
# ('data', '')
# ('headers', EnvironHeaders([('Content-Length', u'0'), ('User-Agent', u'Apifox/1.0.0 (https://apifox.com)'), ('Connection', u'close'), ('Aotbot-Sign', u'Rvq6EQnCHmBAUW58s+PY8g=='), ('Host', u'192.168.9.200:5000'), ('Accept', u'*/*'), ('Aoting-Plaform', u'apifox'), ('Aoting-User', u'apifox'), ('Content-Type', u'application/x-www-form-urlencoded'), ('Accept-Encoding', u'gzip, deflate, br')]))
# ('json', None)


# 云平台
# ('before', <Request 'http://192.168.9.200:5001/check_update' [OPTIONS]>)
# ('data', '')
# ('headers', EnvironHeaders([('Referer', u'http://cloud.aotbot.com/'), ('Origin', u'http://cloud.aotbot.com'), ('User-Agent', u'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'), ('Connection', u'close'), ('Access-Control-Request-Headers', u'aotbot-sign,aoting-plaform,aoting-user,content-type'), ('Sec-Fetch-Mode', u'cors'), ('Host', u'192.168.9.200:5001'), ('Accept', u'*/*'), ('Access-Control-Request-Method', u'GET'), ('Accept-Language', u'zh-CN,zh;q=0.9'), ('Accept-Encoding', u'gzip, deflate')]))
# ('json', None)
# ('before', <Request 'http://192.168.9.200:5001/check_update' [GET]>)
# ('data', '')
# ('headers', EnvironHeaders([('Referer', u'http://cloud.aotbot.com/'), ('Origin', u'http://cloud.aotbot.com'), ('Aotbot-Sign', u'hN+/XqEGXzxdB/PIcqcIJA=='), ('User-Agent', u'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'), ('Connection', u'close'), ('Host', u'192.168.9.200:5001'), ('Accept', u'application/json, text/plain, */*'), ('Aoting-Plaform', u'Cloud_Web'), ('Aoting-User', u'softer'), ('Accept-Language', u'zh-CN,zh;q=0.9'), ('Content-Type', u'application/json'), ('Accept-Encoding', u'gzip, deflate')]))